# -*-coding:utf-8-*-
import struct
import binascii

"""
struct实现颜色rgb值和int值的转换
"""
p = 0xffff00  # 16776960
# int转rgb, c_rgb=c_rgb2=(255, 255, 0)
c_rgb = struct.unpack('>BBB', p.to_bytes(length=3, byteorder='big'))
c_rgb2 = tuple(b for b in p.to_bytes(length=3, byteorder='big'))
# rgb转int, c_int=16776960
c_int = int.from_bytes(struct.pack('>BBB', c_rgb[0], c_rgb[1], c_rgb[2]), byteorder='big')

"""
binary和ascii之间转换
"""
a = b'ab6465'
b = b'\xabde'
# a2b_hex将16进制ascii码转binary
binascii.a2b_hex(a)  # b'ab6465' => b'\xabde',
# b2a_hex将binary转16进制ascii码
binascii.b2a_hex(b)  # b'\xabde' => b'ab6465'
binascii.b2a_hex(a)  # b'ab6465' => b'616236343635'

"""
int和bytes之间转换
"""
c = b'\xff\xff\x00'
d = 16776960
# bytes转int
int.from_bytes(c, byteorder='big')  # 16776960
# int转bytes
d.to_bytes(length=3, byteorder='big')  # b'\xff\xff\x00'

"""
int[]和bytes之间转换
"""
# 将bytes中的每个字节转为对应的十进制ascii码列表
list(b'\xabde')  # [171, 100, 101]
# 将十进制ascii码列表转为对应bytes
x = bytes([171, 100, 101])  # b'\xabde'

"""
bytes和hex之间转换
"""
# bytes转hex
b'\xabde'.hex()  # 'ab6465'
# hex转bytes
bytes.fromhex('ab6465')  # b'\xabde'

